package com.downguys.exception;

/**
 * 异常基础类
 *
 * @author xiyang.qiao
 * @date 2017/1/3 - 18:10
 */
public class UserException extends RuntimeException{

    private static final long serialVersionUID = 1L;

    public static final int GENERAL_EXCEPTION = -123456789;

    /**
     * 错误码
     */
    protected int returnCode;

    /**
     * 错误描述
     */
    protected String returnMessage;


    public UserException(){
        super();
        this.returnCode = GENERAL_EXCEPTION;
    }


    public UserException(IErrorCode iErrorCode) {
        initException(iErrorCode);
    }

    public UserException(IErrorCode iErrorCode, Throwable cause) {
        super(cause);
        initException(iErrorCode);
    }


    public UserException(IErrorCode iErrorCode, String message){

        initException(iErrorCode);
        this.returnMessage = message;
    }

    public UserException(IErrorCode iErrorCode, String message, Throwable cause){
        super(cause);
        initException(iErrorCode);
        this.returnMessage = message;
    }

    public UserException(Throwable cause){
        super(cause);
        if(cause instanceof UserException){
            copyCause((UserException) cause);
        }else {
            this.returnCode = GENERAL_EXCEPTION;
            this.returnMessage = cause.toString();
        }
    }


    /**
     * 获取返回嘛
     *
     * @return
     */
    public int getReturnCode() {
        return this.returnCode;
    }

    /**
     * 获取返回描述
     */
    public String getReturnMessage() {
        return this.returnMessage;
    }


    private void copyCause(UserException userException){
        this.returnCode = userException.returnCode;
        this.returnMessage = userException.returnMessage;
    }


    private void initException(IErrorCode iErrorCode) {
        if(iErrorCode == null){
            throw new java.lang.IllegalArgumentException("error code could not null.");
        }
        this.returnCode = iErrorCode.getReturnCode();
        this.returnMessage = iErrorCode.getReturnMessage();
    }

}
